"""
详细认证测试脚本
创建时间：2025-09-21
作者：开发团队
目的：详细测试认证过程中的每个步骤
"""

import sys
import os

# 添加项目路径
sys.path.append(os.path.join(os.path.dirname(__file__), 'backend', 'src'))

# 设置环境变量
os.environ['ENVIRONMENT'] = 'development'

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from backend.src.models.user import User
from backend.src.core.security import verify_password
from backend.src.core.config import get_config
from backend.src.services.auth_service import get_user_by_username

def test_database_connection():
    """测试数据库连接"""
    print("测试数据库连接...")
    
    try:
        # 获取配置
        config = get_config()
        print(f"数据库URL: {config.DATABASE_URL}")
        
        # 创建数据库引擎
        engine = create_engine(config.DATABASE_URL, echo=False)
        
        # 创建会话
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        db = SessionLocal()
        
        # 查询用户
        user = db.query(User).filter(User.username == "guard001").first()
        if user:
            print(f"找到用户: {user.username}")
            print(f"用户ID: {user.id}")
            print(f"用户角色: {user.role}")
            print(f"密码哈希: {user.password_hash}")
        else:
            print("未找到用户")
        
        db.close()
        return user
    except Exception as e:
        print(f"数据库连接测试出错: {e}")
        import traceback
        traceback.print_exc()
        return None

def test_auth_service():
    """测试认证服务"""
    print("\n测试认证服务...")
    
    try:
        # 获取配置
        config = get_config()
        
        # 创建数据库引擎
        engine = create_engine(config.DATABASE_URL, echo=False)
        
        # 创建会话
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        db = SessionLocal()
        
        # 使用认证服务获取用户
        user = get_user_by_username(db, "guard001")
        if user:
            print(f"认证服务找到用户: {user.username}")
            print(f"用户ID: {user.id}")
            print(f"用户角色: {user.role}")
            print(f"密码哈希: {user.password_hash}")
        else:
            print("认证服务未找到用户")
        
        db.close()
        return user
    except Exception as e:
        print(f"认证服务测试出错: {e}")
        import traceback
        traceback.print_exc()
        return None

def test_password_verification():
    """测试密码验证"""
    print("\n测试密码验证...")
    
    try:
        # 获取配置
        config = get_config()
        
        # 创建数据库引擎
        engine = create_engine(config.DATABASE_URL, echo=False)
        
        # 创建会话
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        db = SessionLocal()
        
        # 获取用户
        user = get_user_by_username(db, "guard001")
        if user:
            print(f"用户: {user.username}")
            print(f"密码哈希: {user.password_hash}")
            
            # 测试密码验证
            test_password = "123456"
            is_valid = verify_password(test_password, str(user.password_hash))
            print(f"密码 '{test_password}' 验证结果: {is_valid}")
            
            # 测试错误密码
            wrong_password = "wrongpassword"
            is_valid_wrong = verify_password(wrong_password, str(user.password_hash))
            print(f"错误密码 '{wrong_password}' 验证结果: {is_valid_wrong}")
        else:
            print("未找到用户")
        
        db.close()
    except Exception as e:
        print(f"密码验证测试出错: {e}")
        import traceback
        traceback.print_exc()

def main():
    print("详细认证测试")
    print("=" * 50)
    
    # 测试数据库连接
    user = test_database_connection()
    
    # 测试认证服务
    auth_user = test_auth_service()
    
    # 添加对变量的使用，避免未使用变量警告
    if user:
        print(f"数据库用户信息: {user.username} (ID: {user.id}, 角色: {user.role})")
    else:
        print("数据库连接未返回有效用户")
        
    if auth_user:
        print(f"认证用户信息: {auth_user.username} (ID: {auth_user.id}, 角色: {auth_user.role})")
    else:
        print("认证服务未返回有效用户")
    
    # 测试密码验证
    test_password_verification()
    
    print("\n测试完成")

if __name__ == "__main__":
    main()